package com.ckd.flyingtrip.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.adapter.ServiceShopDetailAdapter;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.javabean.BuycarBean;
import com.ckd.flyingtrip.javabean.CityBean;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.VolleyErrorUtils;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ServiceShopDetailActivity extends BaseActivity {

    @BindView(R.id.activity_service_shopdetail_imageView)
    ImageView imageView;
    @BindView(R.id.activity_service_shopdetail_time)
    TextView time;
    @BindView(R.id.activity_service_shopdetail_business)
    TextView business;
    @BindView(R.id.activity_service_shopdetail_phone)
    TextView phone;
    @BindView(R.id.activity_service_shopdetail_address)
    TextView address;
    @BindView(R.id.activity_service_shopdetail_recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.activity_service_shopdetail_nestedScrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.activity_service_shopdetail_smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.toolber_color_title)
    TextView title;

    private CityBean cityBean;

    private List<BuycarBean.DataBean.ListBean> listBeans = new ArrayList<>();
    private ServiceShopDetailAdapter adapter;

    private int page = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_shopdetail);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();

    }

    private void initView() {
        cityBean = (CityBean) getIntent().getSerializableExtra("text");
        Glide.with(this).load(cityBean.getSiteUrl()).into(imageView);
        title.setText(cityBean.getSiteName());
        time.setText("营业时间：" + cityBean.getSiteBusinessStartTime() + "  —  " + cityBean.getSiteBusinessEndTime());
        String timeNow = new SimpleDateFormat("HH:mm").format(System.currentTimeMillis());
        if (Integer.parseInt(date2TimeStamp(cityBean.getSiteBusinessStartTime(), "HH:mm")) <
                Integer.parseInt(date2TimeStamp(timeNow, "HH:mm")) &&
                Integer.parseInt(date2TimeStamp(timeNow, "HH:mm")) <
                        Integer.parseInt(date2TimeStamp(cityBean.getSiteBusinessEndTime(), "HH:mm"))) {
            business.setText("营业中");
        } else {
            business.setText("休息中");
        }

        phone.setText("联系方式：" + cityBean.getSiteContacts() + "  " + cityBean.getSitePhone());
        address.setText(cityBean.getSiteAddr());

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        linearLayoutManager.setAutoMeasureEnabled(true);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        adapter = new ServiceShopDetailAdapter(this, listBeans);
        recyclerView.setAdapter(adapter);

    }

    private void initData() {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.MAICHEXINXI, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.i("店铺车辆列表", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        BuycarBean bean = new Gson().fromJson(s, BuycarBean.class);
                        if (smartRefreshLayout != null)
                            smartRefreshLayout.setEnableLoadMore(bean.getData().isHasNextPage());
                        listBeans.addAll(bean.getData().getList());
                        if (adapter != null)
                            adapter.notifyDataSetChanged();
                    } else {
                        toast(msg);
                    }
                    if (smartRefreshLayout != null) {
                        smartRefreshLayout.finishLoadMore();
                        smartRefreshLayout.finishRefresh();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                VolleyErrorUtils.checkError(volleyError);
                if (smartRefreshLayout != null) {
                    smartRefreshLayout.finishLoadMore();
                    smartRefreshLayout.finishRefresh();
                }
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("cityId", Constants.CITYID);
                    json_url.put("carType", "");
                    json_url.put("siteNum", cityBean.getSiteNum());
                    json_url.put("page", page);
                    json_url.put("row", 10);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));

                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initListener() {
        adapter.setOnItemClickListener(new ServiceShopDetailAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent inten = new Intent(ServiceShopDetailActivity.this, CarDetailActivity.class);
                inten.putExtra("id", listBeans.get(position).getBicycleId());
                startActivity(inten);
            }
        });

        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                initData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                smartRefreshLayout.setEnableLoadMore(true);
                page = 1;
                listBeans.clear();
                initData();
            }
        });
    }

    @OnClick(R.id.toolber_color_back)
    public void onViewClicked() {
        finish();
    }

    private String date2TimeStamp(String date, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return String.valueOf(sdf.parse(date).getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
